var express = require("express");
var router = express.Router();

// 自定义中间件：确保用户登录
const loginRequired = (req, res, next) => {
  if (!req.session.user) {
    return res.redirect("/auth/login");
  }
  next();
};

// 获取帖子
const getPost = async (db, id, checkAuthor = false) => {
  return await new Promise((resolve, reject) => {
    db.get(
      "SELECT p.id, title, body, created, author_id, username FROM post p JOIN user u ON p.author_id = u.id WHERE p.id = ?",
      [id],
      (err, post) => {
        if (err) return reject(err);
        if (!post)
          return reject({
            status: 404,
            message: `Post id ${id} doesn't exist.`,
          });

        if (checkAuthor && post.author_id != req.session.user.id) {
          return reject({
            status: 403,
            message: "You are not the author of this post.",
          });
        }
        resolve(post);
      }
    );
  });
};

// 路由
router.get("/", async (req, res, next) => {
  const db = req.app.locals.db;
  const posts = await new Promise((resolve, reject) => {
    db.all(
      "SELECT p.id, title, body, created, author_id, username FROM post p JOIN user u ON p.author_id = u.id ORDER BY created DESC",
      (err, rows) => {
        if (err) {
          reject(err);
        }
        resolve(rows);
      }
    );
  });
  res.render("blog/index.html", { posts: posts, user: req.session.user });
});

router.get("/blog/create", loginRequired, (req, res) => {
  res.render("blog/create.html", { user: req.session.user });
});

router.post("/blog/create", loginRequired, async (req, res) => {
  let error = "";
  const { title, body } = req.body;
  const db = req.app.locals.db;

  if (!title) {
    error = "Title is required.";
  }

  if (error) {
    return res.render("auth/create.html", {
      post: { title: title, body: body },
      message: error,
    });
  } else {
    await db.run("INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)", [
      title,
      body,
      req.session.user.id,
    ]);
    res.redirect("/");
  }
});

router.get("/blog/update/:id", loginRequired, async (req, res, next) => {
  const db = req.app.locals.db;
  const post = await getPost(db, req.params.id);
  res.render("blog/update.html", { post: post, user: req.session.user });
});

router.post("/blog/update/:id", loginRequired, async (req, res, next) => {
  let error = "";
  const { title, body } = req.body;
  const db = req.app.locals.db;

  if (!title) {
    error = "Title is required.";
  }

  if (error) {
    return res.render("auth/update.html", {
      post: { title: title, body: body },
      message: error,
    });
  } else {
    await db.run("UPDATE post SET title = ?, body = ? WHERE id = ?", [
      title,
      body,
      req.params.id,
    ]);
    res.redirect("/");
  }
});

router.post("/blog/delete/:id", loginRequired, (req, res, next) => {
  const db = req.app.locals.db;
  getPost(db, req.params.id)
    .then(() => {
      db.run("DELETE FROM post WHERE id = ?", [req.params.id], (err) => {
        if (err) return next(err);
        res.redirect("/");
      });
    })
    .catch((err) => {
      if (err.status) return res.status(err.status).send(err.message);
      next(err);
    });
});

module.exports = router;
